<?php

namespace app\modules\adminstore\controllers;

use Yii;
use app\components\AdminController;
use common\models\Store;
use common\models\SysUser2role;
use common\models\Tools;

/**
 * Default controller for the `adminstore` module
 */
class DefaultController extends AdminController
{
    public $enableCsrfValidation = false;
    /**
     * 店铺列表
     * @return string
     */
    public function actionIndex()
    {
        $userid = Yii::$app->user->identity->id;
        $region_3 = Yii::$app->user->identity->region_3;
        //获取当前用户的角色
        
        
        $condition = [];
        $page_no = Tools::GetSafeParam('page_no', 1, 0);
        $condition['name'] = Tools::GetSafeParam('name', '', 1);
        $condition['userid'] = Tools::GetSafeParam('userid', '', 1);
        
        
        $roleid = \common\models\SysUser2role::getUserRoleId($userid);
        switch ($roleid){
            case 1://管理员，查看所有店铺

                $data = Store::getBackendStoreList($condition,$page_no);

                $page = Tools::showCmPager($page_no, $data['perpage'], $data['total'],$condition);
                break;
            case 2://区域代理商，查看所属区域的普通店铺
                $condition['region_3'] = $region_3;
                $condition['type'] = 2;
                $data = Store::getBackendStoreList($condition,$page_no);

                $page = Tools::showCmPager($page_no, $data['perpage'], $data['total'],$condition);
                break;
            default:
                
        }
        $status_arr = array(0=>'待审核',1=>'已通过',2=>'未通过');
        return $this->render('index',[
            'data' => $data,
            'page' => $page,
            'condition' => $condition,
            'status_arr' =>$status_arr,
        ]);
    }
    
    public function actionAuth(){
        $id = Tools::GetSafeParam('id', 0, 0);
        $status = Tools::GetSafeParam('status', '', 0);
        $reason = Tools::GetSafeParam('reason', '', 1);
        
        $model = Store::findOne($id);
        
        $userid = Yii::$app->user->identity->id;
        $region_3 = Yii::$app->user->identity->region_3;
        //获取当前用户的角色
        $roleid = \common\models\SysUser2role::getUserRoleId($userid);
        
        //权限检测
        if($roleid == 1){
            //do nothing
        }else if($roleid == 2){
            if($model->region_3 != $region_3){
                Tools::get_show_msg('/adminstore/default/index', '没有权限', 1, 3);
            }
        }else{//其他角色没有审核商家的权限
            Tools::get_show_msg('/adminstore/default/index', '没有权限', 1, 3);
        }
        
        //保存提交的
        if($status != ""){
            if($status==2 && $reason == ""){
                $output['success'] = 0;
                $output['msg'] = "请输入未通过原因！";
                Tools::outputjson($output);
            }
            $model->reason = $reason;
            $model->status=$status;
            
            $transaction = Yii::$app->db->beginTransaction();
            try{
                if(!$model->save(false)){
                    \Yii::getLogger()->log($model->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('系统错误！');
                }
                
                $store_user_role = $model->type==1 ? 2:3;
                
                $user_role_model = SysUser2role::findOne(['userid'=>$model->userid]);
                
                if(!empty($user_role_model)){
                    if($user_role_model->roleid != $store_user_role){
                        $user_role_model->roleid = $store_user_role;
                        if(!$user_role_model->save(false)){
                            \Yii::getLogger()->log($user_role_model->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('更新原有用户角色出错！');
                        }
                    }
                }else{
                    $new_role_model = new SysUser2role();
                    $new_role_model->userid = $model->userid;
                    $new_role_model->roleid = $store_user_role;
                    $new_role_model->addtime = time();
                    if(!$new_role_model->save(false)){
                        \Yii::getLogger()->log($new_role_model->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('初始化用户角色出错！');
                    }
                }
                
                $user_model = \common\models\User::findOne($model->userid);
                if($user_model->region_3 != $model->region_3){
                    $user_model->region_1 = $model->region_1;
                    $user_model->region_2 = $model->region_2;
                    $user_model->region_3 = $model->region_3;
                    if(!$user_model->save(false)){
                        \Yii::getLogger()->log($user_model->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('初始化用户区域出错！');
                    }
                }
                
                $transaction->commit();
            } catch (\Exception $e){
                $transaction->rollBack();
                
                $output['success'] = 0;
                $output['msg'] = $e->getMessage();
                Tools::outputjson($output);
            }
            
            $output['success'] = 1;
            $output['msg'] = '提交成功';
            Tools::outputjson($output);
        }
        
        $status_arr = array(0=>'待审核',1=>'已通过',2=>'未通过');
        $type_arr = array(1=>'区域代理商',2=>'普通商家');
        $liaison_id_type_arr = array(1=>'身份证',2=>'护照',3=>'港澳通行证',4=>'军官证');
           
        $province = \common\models\Region::getRegionNameById($model->region_1);
        $city = \common\models\Region::getRegionNameById($model->region_2);
        $county = \common\models\Region::getRegionNameById($model->region_3);
        return $this->render('auth',[
            'model' => $model,
            'status_arr' =>$status_arr,
            'type_arr'=>$type_arr,
            'liaison_id_type_arr'=>$liaison_id_type_arr,
            'front_sever'=>$key = Yii::$app->params['server'],
            'province'=>$province,
            'city'=>$city,
            'county'=>$county,
        ]);
    }
}
